<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css"
      crossorigin="anonymous"
    />
    <style>
      .form-control-plaintext {
        border: 1px solid #000;
        margin-right: 20px;
      }
      .pagination {
        justify-content: flex-end;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <!-- 搜索 -->
      <form class="form-inline" style="float: left">
        <div class="form-group mb-2">
          <label for="name" class="sr-only">姓名</label>
          <input
            type="text"
            class="form-control-plaintext"
            id="name"
            placeholder="姓名"
          />
        </div>
        <button class="btn btn-primary mb-2 search" style="margin-right: 10px">
          搜索
        </button>
        <button class="btn btn-primary mb-2 reset">重置</button>
      </form>

      <button
        type="button"
        class="btn btn-primary"
        data-toggle="modal"
        data-target="#exampleModal"
        style="float: right"
      >
        新增学员
      </button>

      <div
        class="modal fade"
        id="exampleModal"
        tabindex="-1"
        aria-labelledby="exampleModalLabel"
        aria-hidden="true"
      >
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">新增学员</h5>
              <button
                type="button"
                class="close"
                data-dismiss="modal"
                aria-label="Close"
              >
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              <form>
                <div class="form-group">
                  <label for="studentname">姓名</label>
                  <input type="text" class="form-control" id="studentname" />
                </div>
                <div class="form-group">
                  <label for="age">年龄</label>
                  <input type="number" class="form-control" id="age" />
                </div>
                <div class="form-group">
                  <label for="sex">性别</label>
                  <!-- <input type="number" class="form-control" id="sex" /> -->
                  <select class="form-control" id="sex">
                    <option value="">请选择</option>
                    <option value="1">男</option>
                    <option value="2">女</option>
                  </select>
                </div>
                <div class="form-group">
                  <label for="num">学号</label>
                  <input type="number" class="form-control" id="num" />
                </div>
                <div class="form-group">
                  <label for="address">住址</label>
                  <input type="text" class="form-control" id="address" />
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button
                type="button"
                class="btn btn-secondary"
                data-dismiss="modal"
              >
                取消
              </button>
              <button
                type="button"
                class="btn btn-primary submit"
                data-dismiss="modal"
              >
                确定
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 表格 -->
      <table class="table border">
        <thead>
          <tr>
            <th scope="col">姓名</th>
            <th scope="col">年龄</th>
            <th scope="col">性别</th>
            <th scope="col">学号</th>
            <th scope="col">住址</th>
            <th scope="col">操作</th>
          </tr>
        </thead>
        <tbody></tbody>
      </table>

      <!-- 分页 -->
      <nav aria-label="Page navigation example">
        <ul class="pagination"></ul>
      </nav>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js"
      crossorigin="anonymous"
    ></script>
    <script>
      let pageSize = 3;
      let currentPage = 1;

      const ajax = (url, method = "GET", data = {}) => {
        return new Promise((resolve) => {
          $.ajax({
            url: "http://localhost:3000/api" + url,
            method,
            data: {
              ...data,
              pageSize,
              currentPage,
              token: localStorage.getItem("token"),
            },
            dataType: "json",
            success(res) {
              resolve(res);
            },
          });
        });
      };

      // window.onload = () => {
      //   ajax().then((res) => {
      //     console.log(res);
      //   });
      // };

      const getTableData = async (params) => {
        const res = await ajax("/students/list", "GET", params);
        if (res.status === 0) {
          const { list, count } = res;
          // 表格拼接
          let str = "";
          list.forEach((item) => {
            str += `
              <tr>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>${item.sex === 1 ? "男" : "女"}</td>
                <td>${item.num}</td>
                <td>${item.address}</td>
                <td>
                  <button type="button" class="btn btn-warning">编辑</button>
                  <button type="button" class="btn btn-danger" onclick="remove('${
                    item._id
                  }')">删除</button>
                </td>
              </tr>
            `;
          });
          $("tbody").html(str);
          // 分页拼接
          let str2 =
            '<li class="page-item"><a class="page-link" href="#">Previous</a></li>';
          for (let i = 1; i <= Math.ceil(count / pageSize); i++) {
            str2 += `<li class="page-item"><a class="page-link" href="#" onclick="change(${i})">${i}</a></li>`;
          }
          str2 += `<li class="page-item"><a class="page-link" href="#">Next</a></li>`;
          $(".pagination").html(str2);
        } else if (res.status === 1006) {
          alert("token错误");
          location.href = "./login.html";
        }
      };

      window.onload = () => {
        getTableData();
      };

      // 查询
      $(".search").on("click", (e) => {
        e.preventDefault();
        currentPage = 1;
        getTableData({ name: $("#name").val() });
      });

      // 重置
      $(".reset").on("click", (e) => {
        e.preventDefault();
        $("#name").val("");
        getTableData();
      });

      // 分页
      const change = (i) => {
        // console.log(i);
        currentPage = i;
        getTableData();
      };

      // 删除
      // 以后的删除要加二次确认
      const remove = async (id) => {
        // console.log(id);
        const res = await ajax("/students/del", "POST", { id });
        // console.log(res);
        if (res.status === 0) {
          alert("删除成功");
          getTableData();
        } else {
          alert(res.msg);
        }
      };

      // 确认添加
      // 以后是要加正则匹配
      $(".submit").on("click", async () => {
        const res = await ajax("/students/add", "POST", {
          name: $("#studentname").val(),
          age: $("#age").val(),
          sex: $("#sex").val(),
          num: $("#num").val(),
          address: $("#address").val(),
        });
        if (res.status === 0) {
          getTableData();
        } else {
          alert(res.msg);
        }
      });
    </script>
  </body>
</html>
